package net.zjitc.servlet;

import net.zjitc.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created by Administrator on 2017/10/12.
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
       String password = request.getParameter("password");
        User user = new User();
        user.setPassword(password);
        user.setUsername(username);
        //张三不能进来 ，其它都可以
        //登录成功,
        if (!"zhangsan".equals(user.getUsername())){

            //request.setAttribute("user",user);

            //会话，这样重定向后，还可以获得其用户信息
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            //将用户名以cookie的形式发送给客户端，key = username
            Cookie cookie = new Cookie("username",user.getUsername());
           //设置有效时间
            cookie.setMaxAge(24*60*60);
            response.addCookie(cookie);

           // request.getRequestDispatcher("/login/success.jsp").forward(request,response);
            response.sendRedirect("/jspTest/login/success.jsp");
        }else {
            //不成功的时候提示错误信息（请求转发）
            request.setAttribute("msg","用户名或密码错误");
            request.getRequestDispatcher("/login/login.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
